#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int n = matrix.size();
        int m = matrix[0].size();

        int l = 0, r = m - 1;
        int s = 0, x = n - 1;

        int num = n * m;
        vector<int> ans;
        while (l <= r && x >= s) {
            for (int i = l; i <= r; i++)ans.push_back(matrix[s][i]);
            s++;
            if (s > x)break;
            for (int i = s; i <= x; i++)ans.push_back(matrix[i][r]);
            r--;
            if (r < l)break;
            for (int i = r; i >= l; i--)ans.push_back(matrix[x][i]);
            x--;
            if (x < s)break;
            for (int i = x; i >= s; i--)ans.push_back(matrix[i][l]);
            l++;
            if (l > r)break;
        }
        return ans;
    }
};